<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/12/17
 * Time: 15:01
 */

namespace app\index\controller;

use app\admin\model\ShopTable;
use app\index\model\Order;
use app\index\model\OrderFoods;
use app\index\model\ShopCar;
use app\index\model\ShopFoods;
use app\index\model\ShopList;
use app\index\model\Member;
use app\index\controller\PayController as Pay;

class OrderController extends BaseController
{
     //我的订单信息
    public function myOrderData($user_id,$page=1,$limit=10){
        $orderflag=input('param.flag');
        if($orderflag==0){
        }else if($orderflag==1){
            $where['pay_status']=1;
        }else if($orderflag==2){
            $where['pay_status']=2;
            $where['order_status']=0;
        }else if($orderflag==3){
            $where['pay_status']=2;
            $where['order_status']=[1,2];
        }
        $where['user_id']=$user_id;
        $orderData=Order::with(['orderFoods'=>function($query){
            $query->field('order_no,food_name,food_price,image,spec,quantity');
        },'orderShop'=>function($query){
            $query->field('id,shop_name');
        }])->where($where)->order('order_time desc')->page($page,$limit)->select();
        foreach($orderData as $key=>$order){
            foreach ($order['order_foods'] as $k=>$v){
                $order['order_foods'][$k]['image'] = $this->url.$v['image'];
            }
            if($order['pay_status']==1){
                //未支付
                $orderData[$key]['flag']=1;
                $orderData[$key]['flagstatus']='待支付';
            }else if($order['pay_status']==2 && $order['order_status'] == 0){
                //已支付
                $orderData[$key]['flag']=2;
                $orderData[$key]['flagstatus']='待使用';
            }else if($order['pay_status']==2 && $order['order_status'] == 1){
                $orderData[$key]['flag']=0;
                $orderData[$key]['flagstatus']='去评价';
            }else if($order['order_status']==2){
            	$orderData[$key]['flagstatus']='交易成功';
                $orderData[$key]['flag']=3;
            }
            if ($order['pay_type'] == 2 && $order['pay_status'] == 1){
                $orderData[$key]['fucker']=true;
            }else{
                $orderData[$key]['fucker']=false;
            }
        }
        $count=Order::where($where)->select()->count();
        $res=[
            'code'=>1,
            'msg'=>'返回成功',
            'count'=>$count,
            'data'=>$orderData
        ];
        return json($res);
    }

    public function orderEdit($order_no){
        $shop_id = Order::where('order_no',$order_no)->value('shop_id');
        $table_id = Order::where('order_no',$order_no)->value('table_id');
        $order = Order::where('shop_id',$shop_id)->where('table_id',$table_id)
            ->column('order_no');
        OrderFoods::where('order_no','in',$order)->update(['father_no'=>$order_no]);
    }

    //订单详情
    public function orderInfo($order_no,$status){
        if ($status == 1){
            $this->orderEdit($order_no);
            $orderInfo=Order::with(['fatherFoods'=>function($query){
                $query->field('father_no,food_name,food_price,image,spec,quantity');
            },'orderShop'=>function($query){
                $query->field('id,shop_name');
            }])->where('order_no',$order_no)->find();
            $total = [];
            foreach ($orderInfo['father_foods'] as $k=>$v){
                $orderInfo['father_foods'][$k]['image'] = $this->url.$v['image'];
                $total[] = $v['food_price'] * $v['quantity'];
            }
            $orderInfo['order_foods'] = $orderInfo['father_foods'];
            $orderInfo['money'] = array_sum($total);
            unset($orderInfo['father_foods']);
        }else{
            $orderInfo=Order::with(['orderFoods'=>function($query){
                $query->field('order_no,food_name,food_price,image,spec,quantity');
            },'orderShop'=>function($query){
                $query->field('id,shop_name');
            }])->where('order_no',$order_no)->find();
            foreach ($orderInfo['order_foods'] as $k=>$v){
                $orderInfo['order_foods'][$k]['image'] = $this->url.$v['image'];
            }
        }
      if($orderInfo['pay_status']==1){
                //未支付
                $orderInfo['flag']=1;
                $orderInfo['flagstatus']='待支付';
            }else if($orderInfo['pay_status']==2 && $orderInfo['order_status'] == 0){
                //已支付
                $orderInfo['flag']=2;
                if ($orderInfo['pay_type'] == 1){
                  $orderInfo['flagstatus']='待评价';
                }else{
                  $orderInfo['flagstatus']='待使用';
                }
            }else if($orderInfo['pay_status']==2 && $orderInfo['order_status'] == 1){
                $orderInfo['flag']=0;
                $orderInfo['flagstatus']='去评价';
            }else if($orderInfo['order_status']==2){
            	$orderInfo['flagstatus']='交易成功';
                $orderInfo['flag']=3;
            }
        $res=[
            'code'=>1,
            'msg'=>'返回成功',
            'data'=> $orderInfo
        ];
        return json($res);
    }


    public function save(){

    }
    //下单展示页面
    public function orderShow(){
        $user_id = (int)input('post.user_id');
        $shop_id = (int)input('post.shop_id');
        $data['foods'] = ShopCar::where('user_id',$user_id)->where('shop_id',$shop_id)->select()->toArray();
        if (empty($data['foods'])){
            return json(['code'=>0,'msg'=>'无数据']);
        }
        $total = [];
        foreach ($data['foods'] as $k=>$v){
            $total[]= $v['price'] * $v['number'];
            $data['foods'][$k]['image'] = $this->url.$v['image'];
        }
        $data['total'] = array_sum($total);
        $data['shop'] = ShopList::where('id',$shop_id)->field('shop_name')->find();
        return json(['code'=>1,'msg'=>'返回成功','data'=>$data]);
    }




    //下单，支付方式：1=线下支付，2=微信支付
    public function orderDown(){
        $user_id = (int)input('post.user_id');  //用户ID
        $table_no = input('post.table_id')?trim(input('post.table_id')):0;  //桌号
        $shop_id = (int)input('post.shop_id');  //店铺ID
        $pay_type = (int)input('post.pay_type');  //支付方式
        $number  = (int)input('post.number');   //人数
        $content = input('post.content');
        if(!$user_id){
            return json(['code'=>0,'msg'=>'user_id不能为空']);
        }
        if(!$shop_id){
            return json(['code'=>0,'msg'=>'shop_id不能为空']);
        }
        if(!$number){
            return json(['code'=>0,'msg'=>'人数不能为空']);
        }
        if ($table_no){
            $table_id = ShopTable::where('shop_id',$shop_id)->where('table_no',$table_no)->value('id');
        }else{
            $table_id = 0;
        }
        switch ($pay_type){
            case 1;
                $data = $this->lineOff($user_id,$table_id,$shop_id,$number,$content);
                break;
            case 2;
                $data = $this->lineOn($user_id,$table_id,$shop_id,$number,$content);
                break;
            default;
                $data = 0;
        }
        if ($data == 0){
            return json(['code'=>0,'msg'=>'支付方式不存在!']);
        }
        $spike = $this->spike($user_id,$shop_id);
        if ($spike == 2){
            return json(['code'=>0,'msg'=>'秒杀商品库存不足,请重新下单!']);
        }
        $normal = $this->normal($user_id,$shop_id);
        if ($normal == 2){
            return json(['code'=>0,'msg'=>'修改食物销量失败']);
        }
        $order = new Order;
        $orderFood = new OrderFoods;
        $shopList = ShopList::where('id',$shop_id)->field('id,order_number')->find();
        $retO = $order->save($data['order']);
        $retF = $orderFood->saveAll($data['food']);
        if (!$retO && !$retF){
            return json(['code'=>1,'msg'=>'下单失败']);
        }
        ShopList::update(['order_number'=>$shopList['order_number']+1],['id'=>$shopList['id']]);
        ShopCar::where('shop_id',$shop_id)->where('user_id',$user_id)->delete();
        return json(['code'=>1,'msg'=>'下单成功','data'=>$data['order']]);
    }
    //正常菜品处理
    private function normal($user_id,$shop_id){
        $car = ShopCar::where('user_id',$user_id)
            ->where('shop_id',$shop_id)
            ->where('spike',2)->field('food_id,number')->select()->toArray();
        $data = [];
        foreach ($car as $k=>$v){
            $shopFoods = ShopFoods::get((int)$v['food_id']);
            $quality = $shopFoods->quality;
            $shopFoods->quality = (int)$quality + (int)$v['number'];
            $ret = $shopFoods->save();
            if ($ret){
                $data[] = 1;
            }else{
                $data[] = 2;
            }
        }
        if (in_array(2,$data)){
            return 2;
        }
        return 1;
    }
    //秒杀菜品处理
    private function spike($user_id,$shop_id){
        $car = ShopCar::where('user_id',$user_id)
            ->where('shop_id',$shop_id)
            ->where('spike',1)->field('food_id,number')->select()->toArray();
        if (empty($car)){
            return 1;
        }
        $data = [];
        foreach ($car as $k=>$v){
               $shopFoods = ShopFoods::get((int)$v['food_id']);
               $number = $shopFoods->stock - $shopFoods->lock;
               if ((int)$number >= (int)$v['number']){
                   $lock = $shopFoods->lock;
                   $quality = $shopFoods->quality;
                   $shopFoods->lock = (int)$lock + (int)$v['number'];
                   $shopFoods->quality = (int)$quality + (int)$v['number'];
                   $shopFoods->save();
                   $data[] = 1;
               }else{
                   $data[] = 2;
               }
        }
        if (in_array(2,$data)){
            return 2;
        }
        return 1;
    }


    //线下数据
    private function lineOff($user_id,$table_id,$shop_id,$number,$content){
        $car = ShopCar::where('user_id',$user_id)->where('shop_id',$shop_id)->select();
        $order_no = $this->orderNo();
        $total = [];
        $foodInsert= [];
        foreach ($car as $k=>$v){
            $total[]= $v['price'] * $v['number'];
            $food = ShopFoods::get((int)$v['food_id']);
            $foodInsert[]=[
                'user_id'=>$user_id,
                'order_no'=>$order_no,
                'father_no'=>$order_no,
                'food_id'=>$v['food_id'],
                'food_name'=>$v['food_name'],
                'image'=>$v['image'],
                'spec'=>$v['spec'],
                'cook_id'=>0,
                'inventor'=>$food['cook_id'],
                'quantity'=>$v['number'],
                'food_price'=>$v['price']
            ];
        }
        $total = array_sum($total);
        $orderInsert = [
            'user_id'=>$user_id,
            'shop_id'=>$shop_id,
            'table_id'=>$table_id,
            'order_no'=>$order_no,
            'money'  => $total,
            'cost'  => $total,
            'pay_type'=>1,
            'pay_status'=>1,
            'order_time'=>time(),
            'order_number'=>$number,
            'order_status'=>1,
            'content'=>$content,
            'return_status'=>0,
        ];
        return ['order'=>$orderInsert,'food'=>$foodInsert];
    }
    //线上
    private function lineOn($user_id,$table_id,$shop_id,$number,$content){
        $car = ShopCar::where('user_id',$user_id)->where('shop_id',$shop_id)->select();
        $order_no = $this->orderNo();
        $total = [];
        $foodInsert= [];
        foreach ($car as $k=>$v){
            $total[]= $v['price'] * $v['number'];
            $food = ShopFoods::get((int)$v['food_id']);
            $foodInsert[]=[
                'user_id'=>$user_id,
                'order_no'=>$order_no,
                'father_no'=>$order_no,
                'food_id'=>$v['food_id'],
                'food_name'=>$v['food_name'],
                'image'=>$v['image'],
                'spec'=>$v['spec'],
                'cook_id'=>0,
                'inventor'=>$food['cook_id'],
                'quantity'=>$v['number'],
                'food_price'=>$v['price']
            ];
        }
        $total = array_sum($total);
        $orderInsert = [
            'user_id'=>$user_id,
            'shop_id'=>$shop_id,
            'table_id'=>$table_id,
            'order_no'=>$order_no,
            'money'  => $total,
            'cost'  => $total,
            'pay_type'=>2,
            'pay_status'=>1,
            'order_time'=>time(),
            'order_number'=>$number,
            'order_status'=>0,
            'content'=>$content,
            'return_status'=>0,
        ];
        return ['order'=>$orderInsert,'food'=>$foodInsert];
    }

    public function orderAdd(){
        $shop_id = input('post.shop_id');
        $table_no = input('post.table_no');
        $table = ShopTable::where('shop_id',$shop_id)->where('table_no',$table_no)->field('id')->find();
        if (!$table){
            return json(['code'=>0,'msg'=>'桌号不存在']);
        }
        $order = Order::with(['orderFoods'=>function($query){
           $query->field('order_no,food_name,quantity,spec,food_price');
        }])->where('shop_id',$shop_id)->where('table_id',$table['id'])
            ->where('pay_type',1)->where('pay_status',1)
            ->field('user_id,shop_id,order_no')->select()->toArray();
        $data = [];
        $total = [];
        foreach ($order as $item){
            foreach ($item['order_foods'] as $k=>$v){
                $data[] = $v;
                $total[] = $v['food_price'] * $v['quantity'];
            }
        }
        $total = array_sum($total);
        return json(['code'=>1,'msg'=>'返回成功','data'=>$data,'total'=>$total]);
    }
    //线上订单判断
    public function scan(){
        $shop_id = input('post.shop_id');
        $table_no = trim(input('post.table_no'));
        $table = ShopTable::where('shop_id',$shop_id)->where('table_no',$table_no)->value('id');
        $order = Order::where('shop_id',$shop_id)
            ->where('table_id',$table)
            ->where('pay_type',1)
            ->where('pay_status',1)->find();
        if (!$order){
            return json(['code'=>0,'msg'=>'没有未支付订单']);
        }
        return json(['code'=>1,'msg'=>'有未支付订单']);
    }

    //线下订单判断
    public function orderIf(){
        $order_no = input('post.order_no');
        $user_id  = input('post.user_id');
        $order = Order::where('order_no',$order_no)->where('pay_type',1)->where('user_id',$user_id)->find();
        $table = Order::where('shop_id',$order['shop_id'])
            ->where('pay_type',1)
            ->where('pay_status',1)
            ->where('table_id',$order['table_id'])->select();
        if (count($table)>1){
            return json(['code'=>1,'msg'=>'您有多个订单是否统一支付?']);
        }
        return json(['code'=>0,'msg'=>'只有一个未支付订单']);
    }

    //支付
    public function orderPay(){
        $user_id = input('post.user_id');
        $order_no = input('post.order_no');
        if (!$user_id){
            return json(['code'=>0,'msg'=>'user_id不能为空']);
        }
        if (!$order_no){
            return json(['code'=>0,'msg'=>'order_no不能为空']);
        }
        $ip = request()->ip();
        $body = '陕西老胡同餐饮有限公司-买单';
        $total_fee = Order::where('user_id',$user_id)->where('order_no',$order_no)->value('money');
        $openID = Member::where('id',$user_id)->value('openID');
        $total_fee = $total_fee * 100;
        $pay = new Pay();
        $ret = $pay->unified($openID,$order_no,$body,$total_fee,$ip);
        if ($ret['return_code'] == 'SUCCESS'){
            return json(['code'=>1,'msg'=>'请求成功','data'=>$ret]);
        }else{
            return json(['code'=>1,'msg'=>$ret['return_msg']]);
        }
    }
    //微信未支付订单取消
    public function orderDel(){
        $user_id = input('post.user_id');
        $order_no = input('post.order_no');
        $order = Order::where('user_id',$user_id)->where('order_no',$order_no)->find();
        if (!$order){
            return json(['code'=>0,'msg'=>'订单不存在']);
        }
        $orderDel = Order::destroy(['id'=>$order['id']]);
        $foodDel = OrderFoods::destroy(['order_no'=>$order_no]);
        if ($orderDel && $foodDel){
            return json(['code'=>1,'msg'=>'删除成功']);
        }else{
            return json(['code'=>0,'msg'=>'删除失败']);
        }
    }


}